<?php

namespace app\api\controller;
use think\Db;
use think\Log;
use app\store\model\Shanghui;
/**
 * 商会相关的操作
 * Class Coupon
 * @package app\api\controller
 */
class Apply extends Controller
{
    /**
     * 商会列表
     * 
     */
    public function shanghui()
    {
        $param = input('param.');

        $obj = Shanghui::with(['logoImage'])->where("status",90);

        if($param['searchInput']) $obj->where("name",'like','%'.$param['searchInput'].'%');
        if($param['state']){
            $state =$param['state']=='已认证'?1:2;
            $obj->where("auth",$state);
        }
        if($param['area']){$obj->where("area",$param['area']);}
        if($param['type']){$obj->where("type",$param['type']);}
        $list = $obj->order("id desc")->paginate(10)->each(function($item){
            if(mb_strlen($item['name'], 'UTF-8')>12){
                $item['name']=$substring = mb_substr($item['name'], 0, 12).'...';
            }
            return $item;
        });
        return $this->renderSuccess(compact('list'));
    }
    /**
     * 所有申请列表
     * 
     */
    public function lists()
    {
        $user = $this->getUser();
        $list = Db::name("shanghui_user")->where("user_id","=", $user['user_id'])->order("update_time desc")->paginate(10);
        return $this->renderSuccess(compact('list'));
    }
     /**
     * 所有身份
     * 
     */
    public function identity()
    {
        $list['identity']=["会员","会长","副会长","秘书长","副秘书长"];
        $list['Lidentity']=["会长","副会长","秘书长"];
        $list['type']=["商协会","私董会","校友会","俱乐部"];
        $list['area']=["大连市","其他"];
        return $this->renderSuccess($list);
    }
    /**
     * 添加入会申请
     * 
     */
    public function add_user(){
        $user = $this->getUser();
        $param = input('param.');
        $data = [];
        $data['user_id']     = $user['user_id'];       //会员ID
        $data['shanghui_id'] = $param['shanghui_id'];  //shanghui表id
        $data['identity']    = $param['identity'];     //身份
        $data['add_date']    = $param['add_date'];     //入会日期
        $data['update_time'] = date('Y-m-d H:i:s');    //申请时间
        try{
            Db::name("shanghui_user") -> insert($data);
        }
        catch(\Exception $e){
            return $this->renderError("已经申请成功，等待管理员通过！");
        }
        $userData =[];
        $userData["nickName"]   = $param['nickName'];  //姓名
        $userData["phone"]      = $param['phone'];     //电话
        $userData["birth_date"] = $param['birth_date'];//生日
        $userData["gender"]     = $param['gender'];    //性别
        $userData['card_id']    = $param['userNumber'];   //身份证号
        Db::name("user")->where('user_id',$user['user_id']) -> update($userData);
        return $this->renderSuccess([],"申请成功，请耐心等待审核");
    }
     /**
     * 建会申请
     * 
     */
    public function add_shanghui(){
        $user = $this->getUser();
        $param = input('param.');
        $data = [];
        $data['userid']      = $user['user_id'];    //会员ID
        $data['name']        = $param['shanghui_name'];      //商会名称
        $data['contacts']    = $param['nickName'];  //联系人
        $data['tel']         = $param['phone'];       //电话
        $data['identity']    = $param['identity'];  //身份
        $data['type']        = $param['type'];         //社团性质
        $data['area']        = $param['area'];         //地区
        $data['pic']         = $param['image_id'];       //商会证件照片
        $data['logo_id']     = $param['logo_id'];       //商会LOGO
        $data['cardnumber']  = $param['userNumber'];   //身份证号
        $data['add_date']    = $param['add_date'];  //入会日期
        $data['update_time'] = date('Y-m-d H:i:s'); //申请时间
        $info = Db::name("shanghui")->where('name',$data['name'])->find();
        if($info){
            return $this->renderError('商会已经存在！');
        }
        Db::name("shanghui") -> insert($data);
        return $this->renderSuccess([],"申请成功，请等待管理员审核！");
    }
     /**
     * 商会会员列表
     * $status 会员状态
     */
    public function shanghui_user($status,$searchInput=''){
        $user = $this->getUser();
        $obj = Db::name("shanghui_user")->alias('s')
        ->field('u.nickName,u.avatarUrl,u.gender,u.phone,u.card_id,s.identity,u.user_id')
        ->join('user u', 's.user_id = u.user_id', 'LEFT')
        ->where("status",$status)->where("s.shanghui_id",$user['shanghui_id']);
        if($searchInput){
            $obj->where('u.nickName|u.phone','like','%'.$searchInput.'%');
        }
        $list = $obj
        ->order("s.update_time desc")
        ->paginate(10);
        $limit_people = Db::name("shanghui")->where('id',$user['shanghui_id'])->value('people');
        $shanghui_people = Db::name("shanghui_user")->where('shanghui_id',$user['shanghui_id'])->where("status",90)->count();
        $showCount = $shanghui_people.'/'.$limit_people;
        return $this->renderSuccess(compact('list','showCount'));
    }
    /**
     * 商会会员审核
     * 
     */
    public function examine_user(){
        $user = $this->getUser();
        $param = input('param.');
        if($param["status"]==90){
            $user_count = Db::name("shanghui_user")->where("shanghui_id",$user['shanghui_id'])->where('status',90)->count();
            $total_count= Db::name("shanghui")->where("id",$user['shanghui_id'])->value("people");
            if($user_count >= $total_count){
                return $this->renderSuccess(['任意内容'],"商会人数已满，请升级商会！");
            }
        }
        $res = Db::name("shanghui_user")
        ->where("shanghui_id",$user['shanghui_id'])
        ->where('user_id',$param['user_id'])
        ->update(["status"=>$param['status'],"remark"=>$param['remark']]);
        // 通过审核
        if($param["status"]==90 and $res){
            $u = Db::name("user")->where('user_id',$param['user_id'])->find();
            // 如果有商会
            if($u['shanghui_id']){
                $info = Db::name("shanghui_user")->where("shanghui_id",$u['shanghui_id'])->where('user_id',$param['user_id'])->where('status',90)->find();
                // 已经有的商会是无效的
                if(!$info){
                    Db::name("user")->where('user_id',$param['user_id'])->update(["shanghui_id"=>$user['shanghui_id'],'examine_role'=>0,'grade_id'=>0]);
                }
            }else{
                Db::name("user")->where('user_id',$param['user_id'])->update(["shanghui_id"=>$user['shanghui_id']]);
            }
           
        }
        return $this->renderSuccess([],'审核完成！');
    }
     /**
     * 商会基础配置详情
     * 
     */
    public function get_shanghui()
    {
        $user = $this->getUser();
        $shanghui = Db::name("shanghui")->where('id',$user['shanghui_id'])->find();
        // 查询当前商会的管理
        $shanghui_manager = Db::name("user")->where('shanghui_id',$user['shanghui_id'])->where('grade_id','>',0)->select();
        // 查询当前商会的非管理
        $shanghui_user = Db::name("user")->where('shanghui_id',$user['shanghui_id'])->where('grade_id',0)->select();
        // 商会等级（产品）
        $shanghui_grade=[
            ['id'=>"1","type"=>1,"people"=>10,'limit'=>1,'price'=>'99'],
            ['id'=>"2","type"=>2,"people"=>100,'limit'=>0,'price'=>'900'],
        ];
        return $this->renderSuccess(['shanghui'=>$shanghui,'manager'=>$shanghui_manager,'user'=>$shanghui_user,'good_grade'=>$shanghui_grade]);
    }
     /**
     * 商会基础配置编辑
     * 
     */
    public function edit_shanghui()
    {
        $user = $this->getUser();
        $param = input('param.');
        $data=[
            'wx_mchid'=>$param['wx_mchid'],
            'wx_apikey'=>$param['wx_apikey'],
            'wx_apiclient_cert'=>$param['wx_apiclient_cert'],
            'wx_apiclient_key'=>$param['wx_apiclient_key'],
        ];
        Db::name("shanghui")->where('id',$user['shanghui_id'])->update($data);
        return $this->renderSuccess([],'编辑成功');
    }
    /**
     * 商会管理员设置
     * 10007分队管理，10008代表处管理，10009分队管理+代表处管理
     */
    public function edit_manager(){
        $user = $this->getUser();
        $param = input('param.');
        Db::name("user")
            ->where('user_id',$param['user_id'])
            ->where('shanghui_id',$user['shanghui_id'])
            ->update(['grade_id'=>$param['grade_id']]);
        Db::name("shanghui_user")
            ->where('user_id',$param['user_id'])
            ->where('shanghui_id',$user['shanghui_id'])
            ->update(['grade_id'=>$param['grade_id']]);    
        return $this->renderSuccess([],'设置成功');
    }
}